# -*- codeing = utf-8 -*-
# @Time :  10:30
# @Author : 张宾
# @File : index.py
# @Software : PyCharm
from io import BytesIO

import ddddocr
from PIL import Image
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
import time
from selenium.webdriver.common.by import By
from selenium.webdriver import Chrome, Keys
from selenium.webdriver import ChromeOptions
from selenium.webdriver.common.action_chains import ActionChains

#规避检测
s = Service(executable_path=r'D:\Google\driver\chromedriver.exe')
driver = webdriver.Chrome(service=s)
option = ChromeOptions()
option.add_experimental_option('excludeSwitches', ['enable-automation'])
driver = Chrome(options=option)

#启动
def start():
    driver.maximize_window()  # 一定要窗口最大化处理
    # 输入网址
    driver.get("http://xgxlsg.cqbvc.edu.cn:17535/SPCP/Web/")
    runNext(driver)
    condition=isElementExist(driver)
    if condition:
        driver.find_element(By.XPATH, '//*[@id="layui-m-layer0"]/div[2]/div/div/div[2]/span').click()
        runAll(driver)
    else:
        addInfo(driver)

#输入账号  密码
def runNext(driver):
    #定位到账号
    driver.find_element(By.ID,"StudentId").clear()
    time.sleep(1)

    
    #向账号输入 值
    driver.find_element(By.ID,"StudentId").send_keys("账号")
    time.sleep(1)

    #定位到密码
    driver.find_element(By.ID,"Name").clear()
    time.sleep(1)

    #向密码输入值
    driver.find_element(By.ID,"Name").send_keys("密码")
    time.sleep(1)

    url=downloadImg(driver)
    code=analysisImg(url)

    #输入验证码
    driver.find_element(By.ID, "codeInput").clear()
    driver.find_element(By.ID,"codeInput").send_keys(code)
    time.sleep(1)

    #点击按钮
    driver.find_element(By.ID,"Submit").send_keys(Keys.ENTER)
    time.sleep(2)

#判断验证码识别正确没
def isElementExist(driver):
    flag=True
    try:
        driver.find_element(By.XPATH, '//*[@id="layui-m-layer0"]/div[2]/div/div/div[2]/span')
    except:
        flag=False
    return flag

#截图验证码
def downloadImg(driver):
    # # 执行js，对页面进行缩放，100 占 125 的 80%
    driver.execute_script('document.body.style.zoom="0.8"')
    # 要截图的元素
    element = driver.find_element(By.ID,"code-box")
    # 坐标
    x, y = element.location.values()
    # 宽高
    h, w = element.size.values()
    # 把截图以二进制形式的数据返回
    image_data = driver.get_screenshot_as_png()
    # 以新图片打开返回的数据
    screenshot = Image.open(BytesIO(image_data))
    # 对截图进行裁剪
    result = screenshot.crop((x, y, x + w, y + h))
    # 显示图片
    # result.show()
    url="one.png"
    result.save(url)
    return url

#解析验证码
def analysisImg(url):
    #机器训练的库 ddddocr
    ocr = ddddocr.DdddOcr()
    with open(url, 'rb') as f:
        img_bytes = f.read()
    res = ocr.classification(img_bytes)
    return res

#执行全部
def runAll(driver):
    runNext(driver)
    # 判断是否正确验证码
    condition = isElementExist(driver)
    if condition:
        driver.find_element(By.XPATH, '//*[@id="layui-m-layer0"]/div[2]/div/div/div[2]/span').click()
        runAll(driver)
    else:
        addInfo(driver)

#填报信息
def addInfo(driver):
    # 点击
    driver.find_element(By.ID, "platfrom2").click()
    time.sleep(1)
    # 执行js代码  选择区域  这可以根据你的地区更改
    select = '''
                    var select=document.getElementsByName("County")[0];
                	for(let i=0;i<select.options.length;i++){
                		console.log(select.options[i].value)
                		if(select.options[i].value=='330602'){
                			select.options[i].selected = true;
                		}
                	}
                 '''
    driver.execute_script(select)
    time.sleep(1)

    # 点击我同意
    checked='''document.getElementById("ckCLS").checked=true;
            let btn=document.getElementsByClassName("save_form");
	        console.log(btn);
	        btn[0].disabled=false;
	        btn[0].className='save_form'
            '''
    driver.execute_script(checked)
    time.sleep(1)

    target=driver.find_element(By.XPATH,'//*[@id="SaveBtnDiv"]/button')
    #鼠标单击
    ActionChains(driver).click(target).perform()
    time.sleep(1)

    driver.close()

if __name__ == '__main__':
    start()

